<?php
/**
 * 权限资源分配组
 */

namespace Plu\Library\Models\Platform\Permission;

use Phalcon\Mvc\Model,
    Phalcon\Db\Column;

class PermissionResource extends Model {
    const CACHE_TIME = 60 * 3;

    public $Id;

    public $Title;

    public $CategoryId;

    public $Sort;

    public $Type;

    public $Identifie1;

    public $Identifie2;

    public function getSource() {
        return 'PermissionResource';
    }

    public function initialize() {
        $this->setReadConnectionService('db.platform.slave');
        $this->hasMany('Id', 'Plu\Library\Models\Platform\Permission\PermissionResourceOfRole', 'ResourceId', array( 'alias' => 'PermissionResourceOfRole' ));
    }

    /**
     * 根据资源标识获取权限
     */
    static public function getResourceByIdentification($tag, $roles = null) {
        list($t1, $t2) = explode(".", $tag);
        if (empty($t1) || empty($t2) ) {
            return false;
        }
        $guid = sprintf('permission_resource_%s_%s', $t1, $t2);

        $parameters = array(
            'Identifie1' => $t1,
            'Identifie2' => $t2
        );

        $data = self::findFirst(array(
            'Identifie1 = :Identifie1: AND Identifie2 = :Identifie2:',
            'bind'		 => $parameters,
            'bindTypes'  => array(
                'Identifie1' => Column::BIND_PARAM_STR,
                'Identifie2' => Column::BIND_PARAM_STR,
            ),
            'cache'		 => array(
                'key'    => $guid,
                'lifetime' => self::CACHE_TIME
            )
        ));

        if (count($data) == 0 || !$data) {
            return false;
        }

        if (is_null($roles)) {
            return false;
        } else {
            $resourceId = $data->Id;
            $role = $data->getPermissionResourceOfRole(array(
                'ResourceId = :resourceId:',
                'bind'	=> array(
                    'resourceId' => $resourceId
                ),
                'bindTypes' => array(
                    'resourceId' => Column::BIND_PARAM_INT
                ),
                'cache'		=> array(
                    'key'	   => sprintf('%s_role_%d', $guid, $resourceId),
                    'lifetime' => self::CACHE_TIME
                )
            ));
            if (count($role) == 0) {
                return false;
            } else {
                $allow_roles = array_column($role->toArray(), 'RoleId');
                $allowable = false;
                for ($c = 0, $len = count($roles); $c < $len; $c++) {
                    $r = $roles[$c];
                    if (in_array($r, $allow_roles)) {
                        $allowable = true;
                        break;
                    }
                }
                return $allowable;
            }
        }
    }
}

?>
